﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using log4net;
using System.Drawing;

namespace QualityRpt.Utils
{
    /// <summary>
    /// ImageUtils 的摘要说明
    /// </summary>
    public class ImageUtils
    {
        static ILog logger = LogManager.GetLogger("ImageUtils");
        public ImageUtils()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        public static bool CreateThumbnailImage(string bigFilePath, string breviaryFilePath, int thumbWidth, int thumbHeigth)
        {
            // 在此处放置用户代码以初始化页面
            bool IsTrue = true;
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(bigFilePath);

            int towidth = thumbWidth;
            int toheight = thumbHeigth;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (ow >= thumbWidth || oh >= thumbHeigth)
            {
                if (ow > oh)
                {
                    toheight = oh * towidth / ow;
                    if (toheight > thumbHeigth)
                    {
                        towidth = ow * thumbHeigth / oh;
                        toheight = thumbHeigth;
                    }
                }
                else if (oh > ow)
                {
                    towidth = ow * toheight / oh;
                    if (towidth > thumbWidth)
                    {
                        toheight = oh * thumbWidth / ow;
                        towidth = thumbWidth;
                    }
                }
            }
            else if (ow < thumbWidth && oh < thumbHeigth)
            {
                towidth = ow;
                toheight = oh;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                int level = 70; //缩略图的质量 1-100的范围
                System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                System.Drawing.Imaging.ImageCodecInfo ici = null;
                foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                        ici = codec;
                }
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters();
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level); //字串1
                //以jpg格式保存缩略图
                bitmap.Save(breviaryFilePath, ici, ep);
            }
            catch (System.Exception e)
            {
                IsTrue = false;
                logger.Error(e);
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return IsTrue;
        }

        public static bool CreateThumbnailImageWidth(string bigFilePath, string breviaryFilePath, int thumbWidth, int thumbHeigth)
        {
            // 在此处放置用户代码以初始化页面
            bool IsTrue = true;
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(bigFilePath);

            int towidth = thumbWidth;
            int toheight = thumbHeigth;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (ow > thumbWidth)
            {
                toheight = oh * towidth / ow;
                if (toheight < thumbHeigth)
                {
                    toheight = thumbHeigth;
                    towidth = ow * toheight / oh;
                }
            }
            else
            {
                towidth = ow;
                toheight = oh;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //int level = 70; //缩略图的质量 1-100的范围
                System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                System.Drawing.Imaging.ImageCodecInfo ici = null;
                foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                        ici = codec; ici = codec;

                }
                CaptureImage(bitmap, breviaryFilePath, thumbWidth, thumbHeigth, 0, 0);
            }
            catch (System.Exception e)
            {
                IsTrue = false;
                logger.Error(e);
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return IsTrue;
        }


        public static System.Drawing.Imaging.ImageFormat GetImagetFormatByFileName(string FileName)
        {
            string suffix = FileName.Substring(FileName.LastIndexOf(".") + 1).ToLower();
            if (suffix.Equals("bmp"))
            {
                return System.Drawing.Imaging.ImageFormat.Bmp;
            }
            if (suffix.Equals("emf"))
            {
                return System.Drawing.Imaging.ImageFormat.Emf;
            }
            if (suffix.Equals("exif"))
            {
                return System.Drawing.Imaging.ImageFormat.Exif;
            }
            if (suffix.Equals("gif"))
            {
                return System.Drawing.Imaging.ImageFormat.Gif;
            }
            if (suffix.Equals("icon"))
            {
                return System.Drawing.Imaging.ImageFormat.Icon;
            }
            if (suffix.Equals("jpg") || suffix.Equals("jpeg"))
            {
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            if (suffix.Equals("png"))
            {
                return System.Drawing.Imaging.ImageFormat.Png;
            }
            if (suffix.Equals("tiff"))
            {
                return System.Drawing.Imaging.ImageFormat.Tiff;
            }
            if (suffix.Equals("wmf"))
            {
                return System.Drawing.Imaging.ImageFormat.Wmf;
            }
            return null;
        }

        /// <summary>
        /// 将图片名转换成缩略图的文件名（文件名加上_small）
        /// </summary>
        /// <param name="PictureUrl"></param>
        /// <returns></returns>
        public static string PictureUrlToBreviaryUrl(string PictureUrl)
        {
            if (PictureUrl == null || PictureUrl.IndexOf(".") == -1)
            {
                return PictureUrl;
            }
            else
            {
                return PictureUrl.Insert(PictureUrl.LastIndexOf("."), "_small");
            }
        }
        /// <summary>
        /// 从图片中截取部分生成新图
        /// </summary>
        /// <param name="sFromFilePath">原始图片</param>
        /// <param name="saveFilePath">生成新图</param>
        /// <param name="width">截取图片宽度</param>
        /// <param name="height">截取图片高度</param>
        /// <param name="spaceX">截图图片X坐标</param>
        /// <param name="spaceY">截取图片Y坐标</param>
        public static void CaptureImage(System.Drawing.Image fromImage, string saveFilePath, int width, int height, int spaceX, int spaceY)
        {
            //载入底图
            int x = 0; //截取X坐标
            int y = 0; //截取Y坐标
            //原图宽与生成图片宽 之差
            //当小于0(即原图宽小于要生成的图)时，新图宽度为较小者 即原图宽度 X坐标则为0
            //当大于0(即原图宽大于要生成的图)时，新图宽度为设置值 即width X坐标则为 sX与spaceX之间较小者
            //Y方向同理
            int sX = (int)fromImage.Width - width;
            int sY = (int)fromImage.Height - height;
            if (sX > 0)
            {
                x = sX > spaceX ? spaceX : sX;
            }
            else
            {
                width = (int)fromImage.Width;
            }

            if (sY > 0)
            {
                y = sY > spaceY ? spaceY : sY;
            }
            else
            {
                height = (int)fromImage.Height;
            }

            //创建新图位图
            Bitmap bitmap = new Bitmap(width, height);
            //创建作图区域
            Graphics graphic = Graphics.FromImage(bitmap);
            //截取原图相应区域写入作图区
            graphic.DrawImage(fromImage, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
            //从作图区生成新图
            System.Drawing.Image saveImage = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap());
            //保存图象
            saveImage.Save(saveFilePath);
            //释放资源
            saveImage.Dispose();
            bitmap.Dispose();
            graphic.Dispose();
        }
    }
}
